﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace ScytaleDecrypt.Model
{
    public static class Decrypter {

        private const int DETECTED_WORDS_BOUND = 1;

        private static ProcessedMessage message; 

        private static int messageLength;

        private static int messagePartLength; 

        private static int messagePartCount;

        public static List<string> DecryptedMessages { get; set; }

        public static List<string> DecryptProcessedMessages(ProcessedMessage processedMessagemessage)
        {
            DecryptedMessages = new List<string>();
            message = processedMessagemessage; 
            messageLength = message.sanitizedMessageLength;
            messagePartCount = message.SubMessageCount;
            messagePartLength = message.SubMessageLength;
            RearrangeMessage();
            return DecryptedMessages;
        }

        private static void RearrangeMessage() {
            for (int i = 0; i < messagePartLength; i++) {
                String readableMessage = CreateNewMessage(i);
                SearchForWordsWithin(readableMessage);
            }
        }

        private static String CreateNewMessage( int indexToTakeLettersFrom ) {
            String result = "";
            foreach (var messagePart in message.MessageParts) {
                if(indexToTakeLettersFrom < messagePart.Length)
                    result += messagePart[indexToTakeLettersFrom];
                else
                    result += "";
            }
            return result; 
        }

        private static void SearchForWordsWithin( string readableMessage ) {
            DictionaryComparer.CheckMessageForWords(readableMessage);
            if (DictionaryComparer.foundWords >= DETECTED_WORDS_BOUND) {
                DecryptedMessages.Add(readableMessage);
            }
        }



    }
 }
